package proyecto.ABMCursos;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.ejb.EJB;
import javax.ejb.Remote;
import javax.ejb.Stateful;
import javax.ejb.Stateless;
import javax.interceptor.Interceptors;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

//import org.apache.log4j.Logger;

//import util.Curso;

@Stateless
@Remote(CursoDAOLocal.class)
@Interceptors({LifecycleInterceptor.class})
public class CursoDAO implements CursoDAOLocal{

	@PersistenceContext
	EntityManager entityManager;


	public int save (CursoBE curso){		
		try{			
			entityManager.persist(curso);			
		} 
		catch(Exception e){
			e.printStackTrace();
		}	
		return curso.getIdCurso();
	}
	

	public CursoBE findById(int id) {
		return entityManager.find(CursoBE.class, id);
		
	}

	
	public void merge(CursoBE curso) {
		try{						
			entityManager.merge(curso);
		} 
		catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public List findByName(String name)
	   {	     
	      return entityManager.createQuery("select c from CursoBE c where c.nombre = :nombre").setParameter("nombre", name).getResultList();
	   }
	
	public List findAll() {		
		return entityManager.createQuery("from CursoBE").getResultList();
	}
	
	public void remove(int idCurso){	
		entityManager.remove(entityManager.find(CursoBE.class, idCurso));
	}
	
//	 Callbacks ----------------------------------------------------------------
	   @PostConstruct
	   public void postConstructCallback()
	   {
	      System.out.println("PostConstruct - Have EntityManager: " + (entityManager != null));
	   }

	   @PreDestroy
	   public void preDestroyCallback()
	   {
	      System.out.println("PreDestory - Have EntityManager: " + (entityManager != null));
	   }
}
